<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(suggestion, index) in suggestions"
      :key="index"
      @click="$emit('search', suggestion)"
    >
      <div slot="title" v-html="highlight(suggestion)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
// 防抖函数
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      // 联想数据建议列表
      suggestions: [],
    }
  },
  computed: {},
  watch: {
    searchText: {
      // 当 searchText 发生变化时 会触发这个函数
      // debounce 函数 为防抖函数
      handler: debounce(function (value) {
        // console.log(value)
        this.loadSearchSuggestions(value)
      }, 200),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(value) {
      try {
        const { data } = await getSearchSuggestion(value)
        this.suggestions = data.data.options
        // console.log(this.suggestions)
      } catch (err) {
        this.$toast('数据获取失败，请稍后重试')
      }
    },

    // 处理字符串高亮显示
    highlight(suggestion) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return suggestion.replace(reg, highlightStr)
    },
  },
}
</script>
<style lang='less' scoped>
.search-suggestion {
  /deep/ span.active {
    color: red;
  }
}
</style>
